package com.clkj.cldisabledmanclient.mvp.main.personalcenter;

import android.Manifest;
import android.content.Intent;
import android.os.Bundle;
import android.provider.SyncStateContract;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.clkj.cldisabledmanclient.R;
import com.clkj.cldisabledmanclient.app.AppManager;
import com.clkj.cldisabledmanclient.base.BaseFragment;
import com.clkj.cldisabledmanclient.bean.PersonInfo;
import com.clkj.cldisabledmanclient.bean.VersionInfoBean;
import com.clkj.cldisabledmanclient.constant.Common;
import com.clkj.cldisabledmanclient.constant.Config;
import com.clkj.cldisabledmanclient.constant.ShareKey;
import com.clkj.cldisabledmanclient.http.HttpConfig;
import com.clkj.cldisabledmanclient.http.OkGoUpdateHttpUtil;
import com.clkj.cldisabledmanclient.mvp.homerecovertrain.HomeRecoverTrainActivity;
import com.clkj.cldisabledmanclient.mvp.login.ActivityLogin;
import com.clkj.cldisabledmanclient.mvp.myaction.MyActionActivity;
import com.clkj.cldisabledmanclient.mvp.myapply.MyApplyListActivity;
import com.clkj.cldisabledmanclient.mvp.myenvalue.MyEnvalueActivity;
import com.clkj.cldisabledmanclient.mvp.myrecoverorg.ActivityMyRecoverOrg;
import com.clkj.cldisabledmanclient.mvp.myrecoverplan.MyRecoverPlanActivity;
import com.clkj.cldisabledmanclient.mvp.myrecovertrain.MyRecoverTrainActivity;
import com.clkj.cldisabledmanclient.mvp.satisfactionresearch.SatisfationResearchActivity;
import com.clkj.cldisabledmanclient.util.AppUtils;
import com.clkj.cldisabledmanclient.util.CProgressDialogUtils;
import com.clkj.cldisabledmanclient.util.CommonUtil;
import com.clkj.cldisabledmanclient.util.DesUtil;
import com.clkj.cldisabledmanclient.util.LogUtil;
import com.clkj.cldisabledmanclient.util.SPUtils;
import com.clkj.cldisabledmanclient.util.ToastUtil;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.mylhyl.acp.Acp;
import com.mylhyl.acp.AcpListener;
import com.mylhyl.acp.AcpOptions;
import com.vector.update_app.UpdateAppBean;
import com.vector.update_app.UpdateAppManager;
import com.vector.update_app.UpdateCallback;
import com.vector.update_app.listener.ExceptionHandler;
import com.vector.update_app.listener.IUpdateDialogFragmentListener;

import org.json.JSONObject;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cz.msebera.android.httpclient.Header;
/*import cz.msebera.android.httpclient.HttpRequest;*/

/**
 * Created by clboys on 2019/5/19.
 */

public class FragmentPersonalCenter extends BaseFragment implements View.OnClickListener {


    public String mArgument;

    public static final String ARGUMENT = "argument";

    //默认的是isFirstVisibles true ,刚进来的时候分两种情况
    //1.如果切过来的时候 setVisibleHint在OnCreate之前调用，那isFirstVisible为true，这个时候不进行任何操作；
    //等方法执行到onActivityCreated的时候，在执行一次setUserVisibleHint 这个时候把默认的是isFirstVisibles 设为false
    //然后这个时候调用setUserVISIBLEhINT为true  去获取数据
    //2.如果是后面再次切过来，那isFirstVisible已经为false，那就可以直接通过setUserVisibleHint获取数据了

    //代表这个界面是不是第一次被使用
    boolean isFirstUsed = true;
    boolean isGetData = false;
    private RelativeLayout mRlTitle;
    private ImageView mIvBack;
    private TextView mTvTitle;
    private TextView mTvRight;
    private TextView mTvActionExistAccount;
    private ImageView mIvUserHead;
    private TextView mTvUserName;
    //private TextView mTvUserTel;
    private TextView mTvUserIdcard;
    private TextView mTvMyRecoverOrg;
    private TextView mTvMyAction;
    private TextView mTvMyApply;
    private TextView mTvMyAssess;
    private TextView mTvMyRecoverTrainPlan;
    private TextView mTvMyRecoverTrainRecord;
    private TextView mHomeRecoverTrain;
    private TextView mTvAboutUs;
    private TextView mTvVersionUpdate;
    private TextView tvSatisfactionResearch;

    public static FragmentPersonalCenter getInstance(String argument) {
        Bundle bundle = new Bundle();
        bundle.putString(ARGUMENT, argument);

        FragmentPersonalCenter fragment = new FragmentPersonalCenter();
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        super.onCreateView(inflater, container, savedInstanceState);
        return inflater.inflate(R.layout.fragment_personal_center, container, false);
    }


    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initData();
        assignView(view);
        initView();
        initTitle(view, null, null, "个人中心", false, null);

        String idCard = (String) CommonUtil.getShareValue(ShareKey.USER_IDCARD, "");
        String userName = (String) CommonUtil.getShareValue(ShareKey.USER_NAME, "");

        mTvUserName.setText(userName);
        mTvUserIdcard.setText(idCard);
    }


    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        //fragment 可见的情况下 进行加载数据。不可见则不加载
        if (getUserVisibleHint() == true) {
            if (isFirstUsed == true) {
                isFirstUsed = false;
                setUserVisibleHint(true);
            }
            //不可见，说明fragment已经初始话完成,就直接把isFirstVisible改为false 再次切过来的时候就直接可以加载数据了
        } else {
            isFirstUsed = false;
        }
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        // LogUtil.e("CartVisible");
        if (getUserVisibleHint()) {
            LogUtil.e("MyShuoShuoVisible");
            //如果不是firstvisible才去进行下面的操作  因为第一次很可能出现各种问题
            if (isFirstUsed == false) {
                if (isGetData == false) {

                    //获取数据
                    //getPersonInfo();
                }

            }
        } else {
            LogUtil.e("faXianFragmentVisible");
        }
    }

    //获取用户信息
    private void getPersonInfo() {

        AsyncHttpClient asyncHttpClient = new AsyncHttpClient();
        RequestParams params = new RequestParams();
        String idCard = (String) CommonUtil.getShareValue(ShareKey.USER_IDCARD, "");
        params.put("IdCard", idCard);
        asyncHttpClient.post(HttpConfig.URL_OF_INTERFACE_BASE + "/CDPFIN/getPersonInfo", params, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {

                String response = new String(responseBody);
                JsonObject object = new Gson().fromJson(response, new TypeToken<JsonObject>() {
                }.getType());
                String jsonStr = object.get(Common.RESPONSE_KEY_DATA).getAsString();
                String data = null;
                try {
                    data = DesUtil.decryptDESCBC(jsonStr, DesUtil.KEY);
                } catch (Exception e) {
                    e.printStackTrace();
                }

                PersonInfo personInfo = new Gson().fromJson(data, new TypeToken<PersonInfo>() {
                }.getType());

                mTvUserName.setText(personInfo.getName());

            }

            @Override
            public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {

                ToastUtil.showShort(getActivity(), "获取个人信息失败");
            }
        });
    }


    @Override
    public void initData() {

    }

    @Override
    public void assignView(View view) {
        mRlTitle = view.findViewById(R.id.rl_title);
        mIvBack = view.findViewById(R.id.iv_back);
        mTvTitle = view.findViewById(R.id.tv_title);
        mTvRight = view.findViewById(R.id.tv_right);
        mTvActionExistAccount = view.findViewById(R.id.tv_action_exist_account);
        mIvUserHead = view.findViewById(R.id.iv_user_head);
        mTvUserName = view.findViewById(R.id.tv_user_name);
        //mTvUserTel = view.findViewById(R.id.tv_user_tel);
        mTvUserIdcard = view.findViewById(R.id.tv_user_idcard);
        mTvMyRecoverOrg = view.findViewById(R.id.tv_my_recover_org);
        mTvMyApply = view.findViewById(R.id.tv_my_apply);
        mTvMyAssess = view.findViewById(R.id.tv_my_assess);
        mTvMyRecoverTrainPlan = view.findViewById(R.id.tv_my_recover_train_plan);
        mTvMyRecoverTrainRecord = view.findViewById(R.id.tv_my_recover_train_record);
        mTvAboutUs = view.findViewById(R.id.tv_about_us);
        mTvVersionUpdate = view.findViewById(R.id.tv_version_update);
        mHomeRecoverTrain = view.findViewById(R.id.tv_home_recover_train);
        tvSatisfactionResearch = view.findViewById(R.id.tv_satisfaction_research);
        mTvMyAction = view.findViewById(R.id.tv_my_recover_action);
    }

    @Override
    public void initView() {

        mTvMyRecoverOrg.setOnClickListener(this);
        mTvMyApply.setOnClickListener(this);
        mTvMyAssess.setOnClickListener(this);
        mTvMyRecoverTrainPlan.setOnClickListener(this);
        mTvMyRecoverTrainRecord.setOnClickListener(this);
        mTvActionExistAccount.setOnClickListener(this);
        mTvVersionUpdate.setOnClickListener(this);
        mHomeRecoverTrain.setOnClickListener(this);
        tvSatisfactionResearch.setOnClickListener(this);
        mTvMyAction.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {

        switch (v.getId()) {
            //我的康复机构
            case R.id.tv_my_recover_org:
                startActivity(new Intent(getActivity(), ActivityMyRecoverOrg.class));
                break;
            //机构活动
            case R.id.tv_my_recover_action:
                startActivity(new Intent(getActivity(), MyActionActivity.class));
                break;
            //我的申请
            case R.id.tv_my_apply:
                startActivity(new Intent(getActivity(), MyApplyListActivity.class));
                break;

            //我的评估
            case R.id.tv_my_assess:
                startActivity(new Intent(getActivity(), MyEnvalueActivity.class));
                break;
            //我的康复训练计划
            case R.id.tv_my_recover_train_plan:
                startActivity(new Intent(getActivity(), MyRecoverPlanActivity.class));
                break;

            //我的康复训练记录
            case R.id.tv_my_recover_train_record:
                startActivity(new Intent(getActivity(), MyRecoverTrainActivity.class));
                break;

            //居家康复训练
            case R.id.tv_home_recover_train:

                startActivity(new Intent(getActivity(), HomeRecoverTrainActivity.class));
                break;
            //满意度调查
            case R.id.tv_satisfaction_research:
                startActivity(new Intent(getActivity(), SatisfationResearchActivity.class));
                break;
            //版本更新
            case R.id.tv_version_update:

                //授权
                Acp.getInstance(getActivity()).request(new AcpOptions.Builder()
                                .setPermissions(
                                        Manifest.permission.WRITE_EXTERNAL_STORAGE,
                                        Manifest.permission.INSTALL_PACKAGES
                                )
                                .build(),
                        new AcpListener() {
                            @Override
                            public void onGranted() {
                                checkUpdate();
                            }

                            @Override
                            public void onDenied(List<String> permissions) {
                                //makeText(permissions.toString() + "权限拒绝");
                            }
                        });
                break;
            //退出登录
            case R.id.tv_action_exist_account:
                SPUtils.clear(getActivity());
                AppManager.getAppManager().finishAllActivity();
                startActivity(new Intent(getActivity(), ActivityLogin.class));
                break;
        }
    }

    void checkUpdate() {


        Map<String, String> params = new HashMap<String, String>();

        /*params.put("appKey", "ab55ce55Ac4bcP408cPb8c1Aaeac179c5f6f");
        params.put("appVersion", AppUpdateUtils.getVersionName(this));*/
        params.put("versionType", "残疾");
        new UpdateAppManager
                .Builder()
                //必须设置，当前Activity
                .setActivity(getActivity())
                //必须设置，实现httpManager接口的对象
                .setHttpManager(new OkGoUpdateHttpUtil())
                //必须设置，更新地址
                .setUpdateUrl(HttpConfig.URL_OF_INTERFACE_BASE + "CDPFIN/getLatestAPP")
                //全局异常捕获
                .handleException(new ExceptionHandler() {
                    @Override
                    public void onException(Exception e) {
                        e.printStackTrace();
                    }
                })
                //以下设置，都是可选
                //设置请求方式，默认get
                .setPost(true)
                //不显示通知栏进度条
//                .dismissNotificationProgress()
                //是否忽略版本
//                .showIgnoreVersion()
                //添加自定义参数，默认version=1.0.0（app的versionName）；apkKey=唯一表示（在AndroidManifest.xml配置）
                .setParams(params)
                //设置点击升级后，消失对话框，默认点击升级后，对话框显示下载进度，如果是强制更新，则设置无效
//                .hideDialogOnDownloading()
                //设置头部，不设置显示默认的图片，设置图片后自动识别主色调，然后为按钮，进度条设置颜色
                //.setTopPic(R.mipmap.top_8)
                //为按钮，进度条设置颜色。
                .setThemeColor(0xffffac5d)
                //设置apk下载路径，默认是在下载到sd卡下/Download/1.0.0/test.apk
//                .setTargetPath(path)
                //设置appKey，默认从AndroidManifest.xml获取，如果，使用自定义参数，则此项无效
//                .setAppKey("ab55ce55Ac4bcP408cPb8c1Aaeac179c5f6f")
                .setUpdateDialogFragmentListener(new IUpdateDialogFragmentListener() {
                    @Override
                    public void onUpdateNotifyDialogCancel(UpdateAppBean updateApp) {
                        //用户点击关闭按钮，取消了更新，如果是下载完，用户取消了安装，则可以在 onActivityResult 监听到。

                    }
                })
                .dismissNotificationProgress()
                //不自动，获取
//                .setIgnoreDefParams(true)
                .build()
                //检测是否有新版本
                .checkNewApp(new UpdateCallback() {
                    /**
                     * 解析json,自定义协议
                     *
                     * @param json 服务器返回的json
                     * @return UpdateAppBean
                     */
                    @Override
                    protected UpdateAppBean parseJson(String json) {
                        UpdateAppBean updateAppBean = new UpdateAppBean();
                        Log.e("更新内容", json);
                        JsonObject responseResult = new JsonParser().parse(json).getAsJsonObject();

                        if (responseResult.get(Config.RESPONSE_KEY_CODE).getAsString().equals(Config.RESPONSE_STATUS_SUCCESS)) {
                            try {
                                String jsonStr = responseResult.get(SyncStateContract.Constants.DATA).getAsString();
                                String data = DesUtil.decryptDESCBC(jsonStr, DesUtil.KEY);
                                JsonObject jsonObject2 = new JsonParser().parse(data).getAsJsonObject();

                                VersionInfoBean versionInfo = (VersionInfoBean) CommonUtil.formatJsonToObjectWithNoKey(jsonObject2,
                                        new TypeToken<VersionInfoBean>() {
                                        });
                                int newVerCode = Integer.valueOf(versionInfo.getVersionCode());
                                int vercode = AppUtils.getVersionCode(getActivity());
                                String update = "No";
                                if (newVerCode > vercode) {
                                    update = "Yes";
                                }

                                String new_version = "canlian";
                                String apk_file_url = versionInfo.getVersionFile();
                                String update_log = versionInfo.getVersionMessage();

                                boolean constraint = true;


                                JSONObject jsonObject = new JSONObject(json);
                                updateAppBean
                                        //（必须）是否更新Yes,No
                                        .setUpdate(update)
                                        //（必须）新版本号，
                                        .setNewVersion(new_version)
                                        //（必须）下载地址
                                        .setApkFileUrl(apk_file_url)
                                        //（必须）更新内容
                                        .setUpdateLog(update_log)
                                        //大小，不设置不显示大小，可以不设置
                                        .setTargetSize("6M")
                                        //是否强制更新，可以不设置
                                        .setConstraint(constraint);
                                //设置md5，可以不设置
                                //.setNewMd5("");
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                        return updateAppBean;
                    }

                    @Override
                    protected void hasNewApp(UpdateAppBean updateApp, UpdateAppManager updateAppManager) {
                        updateAppManager.showDialogFragment();
                    }

                    /**
                     * 网络请求之前
                     */
                    @Override
                    public void onBefore() {
                        CProgressDialogUtils.showProgressDialog(getActivity());
                    }

                    /**
                     * 网路请求之后
                     */
                    @Override
                    public void onAfter() {
                        CProgressDialogUtils.cancelProgressDialog(getActivity());
                    }

                    /**
                     * 没有新版本
                     */
                    @Override
                    public void noNewApp(String error) {
                        //Toast.makeText(getActivity(), "没有新版本", Toast.LENGTH_SHORT).show();
                    }
                });


    }
}
